<template>
  <div class="panel">
    <el-form
      v-loading="!operate.dataReady || operate.isLoading"
      ref="formRef"
      :rules="operate.rules"
      :model="operate.post"
      class="demo-form-inline"
      label-width="140px">
      <el-row>
        <el-col :span="12">
          <el-form-item prop="eventsName" label="活动名称">
            <el-input
              maxlength="50"
              v-model="operate.post.eventsName"
              style="max-width: 420px"
              placeholder="活动名称"
            ></el-input>
          </el-form-item>
          <el-form-item prop="eventsType" label="活动分类">
            <el-select v-model="operate.post.eventsType" :disabled="operate.isEdit" placeholder="未选择" multiple>
              <el-option
                v-for="item in operate.DataByCode"
                :key="item.id"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="selfSupport" label="是否为自营" required v-if="!operate.isMerchant">
            <el-switch
              :disabled="operate.isEdit"
              v-model="operate.post.selfSupport"
              :active-value="1"
              :inactive-value="0"
              @change="operateFn.changeSelfSupport"
            ></el-switch>
          </el-form-item>
          <template v-if="operate.post.selfSupport == 1">
            <el-form-item prop="feeConfigType" label="活动费用配置">
              <!-- <div style="width:500px;" v-if="operate.post.feeConfigType === 1"> -->
              <template v-if="!operate.isEdit">
                <el-button type="primary" @click="operateFn.gotoDispose">
                  {{operate.tableFeeData.length && !operate.dialogVisible ? '已配置' : '去配置'}}
                </el-button>
              </template>
              <template v-else>
                <span style="color:#67C23A;margin-right:10px">已配置</span>
                <el-button type="primary" @click="operateFn.gotoDispose(operate.isEdit)" round plain>组合费用详情</el-button>
              </template>
              <!-- </div> -->
            </el-form-item>
            <el-form-item required label="人宠信息配置">
              <div style="width:500px;">
                <el-button type="primary" @click="operateFn.gotoPeoplePet">
                  {{ operate.isPeoplePetConfig || operate.isEdit ? '已配置' : '去配置'}}
                </el-button>
              </div>
            </el-form-item>
          </template>
          <el-form-item prop="eventsAddress" label="活动地址">
            <div style="display: flex;">
              <el-input
              v-model="operate.post.eventsAddress"
              style="max-width: 420px"
              :disabled="operate.isEdit"
              placeholder="请选择活动地址"
            >
            </el-input>
            <svg t="1688116746869" style="margin-left: 10px;margin-top: 2px;"  @click="operateFn.chooseAddress" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3424" width="30" height="30"><path d="M894.185422 128.023792 129.814578 445.743994 445.99982 577.744353 571.860343 893.929596Z" fill="#299FFF" p-id="3425"></path></svg>
            </div>
          </el-form-item>
          <el-row>
            <el-form-item prop="signUpDate" label="活动报名时间">
              <el-date-picker
                style="width: 420px"
                v-model="operate.post.signUpDate"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
                :disabled="operate.isEdit"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :disabled-date="operateFn.limitSignUpStartDate"
                @change="operateFn.signUpDateChange"
              />
            </el-form-item>

          </el-row>
          <el-row>
            <el-form-item prop="eventsStartDate" label="活动时间">
              <el-date-picker
                style="width: 420px"
                v-model="operate.post.eventsStartDate"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
                :disabled="operate.isEdit"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :disabled-date="operateFn.limitSignUpStartDate"
                @change="operateFn.eventsDateChange"
              />
            </el-form-item>
          </el-row>
          <el-form-item prop="surfaceDrawing" :label="'活动封面图\n(220px*292px，大小不超过30kb)'">
            <upload-oss
              list-type="picture-card"
              :limit="1"
              :imageUrl="operate.surfaceDrawing"
              :beforeUpload="(e) => operateFn.beforeUpload(e, 30)"
              @upload="(e) => operateFn.afterUpload(e, 'surfaceDrawing')"
            ></upload-oss>
          </el-form-item>
          <el-form-item prop="shareImage" :label="'活动分享图\n(480px*384px，大小不超过40kb)'">
            <upload-oss
                list-type="picture-card"
                :limit="1"
                :imageUrl="operate.shareImage"
                :beforeUpload="(e) => operateFn.beforeUpload(e, 40)"
                @upload="(e) => operateFn.afterUpload(e, 'shareImage')"
            ></upload-oss>
          </el-form-item>
          <el-form-item prop="detailImages" :label="'活动banner图\n(750px*1000px，大小不超过200kb)'">
            <upload-oss
              :limit="9"
              list-type="picture-card"
              :imageUrl="operate.detailImages"
              :beforeUpload="(e) => operateFn.beforeUpload(e, 200)"
              @upload="(e) => operateFn.afterUploadDetailImg(e)"
            ></upload-oss>
          </el-form-item>
          <template v-if="operate.post.selfSupport == 1 && !operate.isMerchant">
            <el-form-item prop="isConfigShare" label="活动分享配置">
              <el-radio-group v-model="operate.post.isConfigShare" :disabled="operate.isEdit">
                <el-radio :label="0">不配置</el-radio>
                <el-radio :label="1">等额计算</el-radio>
              </el-radio-group>
              <div style="width:410px;display:flex" v-if="operate.post.isConfigShare == 1">
                <el-input v-model="operate.post.deductionAmount" placeholder="单人减免费用（元）" type="number" :disabled="operate.isEdit"></el-input>
                <el-input v-model="operate.post.deductionLimitAmount" :disabled="operate.isEdit" style="margin-left: 10px" type="number" placeholder="减免费用上限（元）"></el-input>
              </div>
            </el-form-item>
            <el-form-item prop="isConfigBiscuit" label="小饼干抵扣">
              <el-radio-group v-model="operate.post.isConfigBiscuit" :disabled="operate.isEdit" @change="operateFn.changeCookie">
                <el-radio :label="0">不抵扣</el-radio>
                <el-radio :label="1">抵扣</el-radio>
              </el-radio-group>
              <template v-if="operate.post.isConfigBiscuit === 1">
                <div v-for="(cookie, index) in operate.feeDataPost.deductionConfigList" :key="index">
                  <div style="display: flex;align-items: center;margin-bottom:10px">
                    <el-input v-model="cookie.biscuitAmount" style="width: 200px;margin-right: 10px" placeholder="请填写小饼干数" type="number" :disabled="operate.isEdit" ></el-input>
                    <el-input v-model="cookie.deductionAmount" :disabled="operate.isEdit"  type="number" style="width: 200px;" placeholder="请填写可抵扣金额"></el-input>
                    <template v-if="!operate.isEdit" >
                      <el-icon style="cursor: pointer;" :size="16" v-if="index === 0" @click="operateFn.addCookie(index)"><Plus /></el-icon>
                      <el-icon style="cursor: pointer;" :size="16" v-if="index !== 0" @click="operateFn.removeCookie(index)"><SemiSelect color="#f00" /></el-icon>
                    </template>
                  </div>
                </div>
              </template>
            </el-form-item>
            <el-form-item label="报名回执页提示" prop="warmTips">
              <el-input
                maxlength="20"
                v-model="operate.post.warmTips"
                placeholder="报名回执页提示"
                :disabled="operate.isEdit"
              ></el-input>
            </el-form-item> 
          </template>
          <el-form-item :label="operate.post.selfSupport == 1 ? '报名回执页二维码\n(长宽比1:1，大小不超过10kb)' : '非自营活动二维码\n(长宽比1:1，大小不超过10kb)'" prop="receiptImage">
            <upload-oss
                list-type="picture-card"
                :limit="1"
                :imageUrl="operate.receiptImage"
                :beforeUpload="(e) => operateFn.beforeUpload(e, 10)"
                @upload="(e) => operateFn.afterUpload(e, 'receiptImage')"
              ></upload-oss>
          </el-form-item>
          <el-form-item label="扫码提示" prop="scanCodePrompt">
            <el-input
              maxlength="20"
              v-model="operate.post.scanCodePrompt"
              placeholder="扫码提示"
              :disabled="operate.isEdit"
            ></el-input>
          </el-form-item> 
          <el-form-item prop="sponsor" label="主办单位">
            <el-input
              maxlength="50"
              v-model="operate.post.sponsor"
              style="max-width: 420px"
              placeholder="主办单位"
            ></el-input>
          </el-form-item>
          <el-form-item prop="undertaker" label="承办单位">
            <el-input
              maxlength="50"
              v-model="operate.post.undertaker"
              style="max-width: 420px"
              placeholder="承办单位"
            ></el-input>
          </el-form-item>
          <el-form-item label="上架消息推送" required>
            <el-switch v-model="operate.post.isPushConfig" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item prop="eventsStatus" label="设置上架状态" required>
            <el-radio-group v-model="operate.post.eventsStatus">
              <el-radio :label="0">下架</el-radio>
              <el-radio :label="1">上架</el-radio>
            </el-radio-group>
            <template v-if="operate.post.eventsStatus === 1">
              <el-date-picker v-model="operate.post.listingTime" type="datetime" placeholder="选择上架时间" :disabled-date="operateFn.limitStackiDate" value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详情" prop="detailedInfo">
            <tinymce
              v-model:value="operate.post.detailedInfo"
              style="width: 100%"
              ref="myEditor"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <div style="margin: 0 auto">
          <el-button
            class="submitBtn"
            type="primary"
            plain
            v-if="operate.post.eventsStatus === -1 || !operate.isEdit"
            @click="operateFn.submitPre(formRef, 2)">存为草稿</el-button>
          <el-button
            class="submitBtn"
            type="primary"
            plain
            @click="operateFn.submitPre(formRef, 1)">预览</el-button>
          <el-button
            class="submitBtn"
            type="primary"
            plain
            @click="operateFn.submitPre(formRef, 0)">提交</el-button>
        </div>
      </el-row>
    </el-form>
    <ChooseAddress
      v-model="operate.showAddress"
      @submitCompleted="operateFn.getEventsAddress"
    ></ChooseAddress>
    <el-dialog
      title="费用配置"
      width="800px"
      :close-on-click-modal="false"
      v-model="operate.dialogVisible">
      <div class="dialog-fee">
        <div>
          <div class="title">
            费用类型({{operate.feeDataPost.otherType.length ? 2: 1}} / 2)
            <el-button size="small" type="primary" @click="operateFn.addFeeType" v-if="!operate.feeDataPost.otherType.length" :disabled="operate.isEdit">
              <el-icon><Plus /></el-icon>添加
            </el-button>
          </div>
          <div class="fee-tp">
            <div style="width:100px;margin-bottom:10px">人数</div>
            <div v-for="(item, nameIndex) in operate.feeDataPost.personPetNum" :key="nameIndex">
              <div class="fee-t-ipt">
                <el-input v-model="operate.feeDataPost.personPetNum[nameIndex]" :disabled="operate.isEdit" placeholder="请输入选项" @blur="operateFn.blurFeeType" maxlength="20"></el-input>
                <div style="position:absolute;right:-5px;top:-5px" v-if="operate.feeDataPost.personPetNum.length !== 1 && !operate.isEdit" @click="operateFn.removeOption(0, nameIndex)"><el-icon size="14"><CircleCloseFilled /></el-icon></div>
              </div>
            </div>
            <div style="margin-bottom:10px">
              <el-button type="primary" :disabled="operate.isEdit" @click="operateFn.addOption(0)">添加选项</el-button>
            </div>
          </div>
          <div class="fee-tp" v-if="operate.feeDataPost.otherType.length">
            <div style="width:100px;margin-bottom:10px;display: flex;align-items: center;">
              其他类型
              <div style="width: 20px;margin-left: 10px;cursor: pointer;" v-if="!operate.isEdit">
                <el-icon @click="operateFn.removeFeeType"><SemiSelect color="#f00" /></el-icon>
              </div>
            </div>
            <div v-for="(item, nameIndex) in operate.feeDataPost.otherType" :key="nameIndex">
              <div class="fee-t-ipt">
                <el-input v-model="operate.feeDataPost.otherType[nameIndex]" placeholder="请输入选项" @blur="operateFn.blurFeeType" maxlength="20" :disabled="operate.isEdit"></el-input>
                <div style="position:absolute;right:-5px;top:-5px" v-if="operate.feeDataPost.otherType.length !== 1 && !operate.isEdit" @click="operateFn.removeOption(1, nameIndex)"><el-icon size="14"><CircleCloseFilled /></el-icon></div>
              </div>
            </div>
            <div style="margin-bottom:10px">
              <el-button type="primary" :disabled="operate.isEdit" @click="operateFn.addOption(1)">添加选项</el-button>
            </div>
          </div>
        </div>
        <div>
          <div class="title">费用表格</div>
          <el-table :data="operate.tableFeeData" style="width: 100%" border>
            <el-table-column prop="personPetNum" label="人数">
              <template #default="{row}">
                {{ row.personPetNum }}
              </template>
            </el-table-column>
            <el-table-column prop="otherType" label="其他类型" v-if="operate.feeDataPost.otherType.length">
              <template #default="{row}">
                {{ row.otherType }}
              </template>
            </el-table-column>
            <el-table-column prop="price" label="价格（元）">
              <template #default="{row}">
                <el-input v-model="row.price" type="number" :disabled="operate.isEdit"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="stock" label="库存">
              <template #default="{row}">
                <el-input-number v-model="row.stock" type="number" :min="0" :max="9999" :disabled="operate.isEdit"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="价格是否生效">
              <template #default="{row}">
                <div v-if="!operate.isEdit">
                  <el-switch v-model="row.enable" :active-value="1" :inactive-value="0" />
                </div>
                <div v-else>
                  <el-button :type="row.enable ? 'success' : 'info'">{{ row.enable ? '是' : '否' }}</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="margin-top: 60px;display: flex;align-items: center;justify-content: flex-end;">
          <el-button type="primary" style="margin-right: 40px" @click="operateFn.submitFeeData">确认</el-button>
          <el-button @click="operateFn.closeDispose">取消</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      title="信息收集配置"
      width="800px"
      :close-on-click-modal="false"
      v-model="operate.dialogPeoplePetVisible">
      <div class="dialog-fee">
        <el-form ref="formRef" :rules="operate.rules" :model="operate.post" class="demo-form-inline" label-width="140px">
          <el-form-item prop="eventsName" label="参与人信息">
            <el-radio-group v-model="operate.isCollectPeopleInfo" :disabled="operate.isEdit" class="ml-4">
              <el-radio :label="'1'">收集</el-radio>
              <el-radio :label="'2'">不收集</el-radio>
            </el-radio-group>
            <div style="border:1px solid #909399;width:160px" v-if="operate.isCollectPeopleInfo === '1'">
              <dl v-if="operate.personConfig">
                <dt style="display:flex;border-bottom:1px solid #909399;padding-left:10px;">
                  <div style="width:70px">收集内容</div>
                  <div style="padding:0 10px;border-left:1px solid #909399;">是否必填</div>
                </dt>
                <dd style="display:flex;border-bottom:1px solid #909399;padding-left:10px;">
                  <div style="width:70px">姓名</div>
                  <div style="padding:0 10px;border-left:1px solid #909399;">
                    <el-switch v-model="operate.personConfig.nameEnable" :active-value="1"
              :inactive-value="0" disabled />
                  </div>
                </dd>
                <dd style="display:flex;border-bottom:1px solid #909399;padding-left:10px;">
                  <div style="width:70px">性别</div>
                  <div style="padding:0 10px;border-left:1px solid #909399;">
                    <el-switch v-model="operate.personConfig.sexEnable" :active-value="1"
              :inactive-value="0" disabled />
                  </div>
                </dd>
                <dd style="display:flex;border-bottom:1px solid #909399;padding-left:10px;">
                  <div style="width:70px">手机号</div>
                  <div style="padding:0 10px;border-left:1px solid #909399;">
                    <el-switch v-model="operate.personConfig.phoneEnable" :active-value="1"
              :inactive-value="0" :disabled="operate.isEdit" />
                  </div>
                </dd>
                <dd style="display:flex;padding-left:10px;">
                  <div style="width:70px">生日</div>
                  <div style="padding:0 10px;border-left:1px solid #909399;">
                    <el-switch v-model="operate.personConfig.birthdayEnable" :active-value="1"
              :inactive-value="0" :disabled="operate.isEdit" />
                  </div>
                </dd>
              </dl>
            </div>
          </el-form-item>
          <el-form-item prop="eventsName" label="参与宠物信息">
            <el-radio-group v-model="operate.isCollectPetInfo" :disabled="operate.isEdit" class="ml-4">
              <el-radio :label="'1'">收集</el-radio>
              <el-radio :label="'2'">不收集</el-radio>
            </el-radio-group>
            <div style="border:1px solid #909399;width:160px" v-if="operate.isCollectPetInfo === '1'">
              <dl v-if="operate.petConfig">
                <dt style="display:flex;border-bottom:1px solid #909399;padding-left:10px;">
                  <div style="width:70px">收集内容</div>
                  <div style="padding:0 10px;border-left:1px solid #909399;">是否必填</div>
                </dt>
                <dd style="display:flex;border-bottom:1px solid #909399;padding-left:10px;">
                  <div style="width:70px">宠物名</div>
                  <div style="padding:0 10px;border-left:1px solid #909399;">
                    <el-switch v-model="operate.petConfig.nameEnable" :active-value="1"
              :inactive-value="0" disabled />
                  </div>
                </dd>
                <dd style="display:flex;border-bottom:1px solid #909399;padding-left:10px;">
                  <div style="width:70px">性别</div>
                  <div style="padding:0 10px;border-left:1px solid #909399;">
                    <el-switch v-model="operate.petConfig.sexEnable" :active-value="1"
              :inactive-value="0" disabled />
                  </div>
                </dd>
                <dd style="display:flex;border-bottom:1px solid #909399;padding-left:10px;">
                  <div style="width:70px">生日</div>
                  <div style="padding:0 10px;border-left:1px solid #909399;">
                    <el-switch v-model="operate.petConfig.birthdayEnable" :active-value="1"
              :inactive-value="0" :disabled="operate.isEdit" />
                  </div>
                </dd>
                <dd style="display:flex;padding-left:10px;">
                  <div style="width:70px">品种</div>
                  <div style="padding:0 10px;border-left:1px solid #909399;">
                    <el-switch v-model="operate.petConfig.breedEnable" :active-value="1"
              :inactive-value="0" :disabled="operate.isEdit" />
                  </div>
                </dd>
              </dl>
            </div>
          </el-form-item>
        </el-form>
        <div style="margin-top: 60px;display: flex;align-items: center;justify-content: flex-end;">
          <el-button type="primary" style="margin-right: 40px" @click="operateFn.submitPeoplePet">确认</el-button>
          <!-- <el-button @click="operateFn.closePeoplePet">取消</el-button> -->
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watchEffect, watch } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { useStore } from "@/store";
import UploadOss from "@/components/AliOSS";
import ChooseAddress from "@/components/address/chooseAddress.vue";
import Tinymce from "@/components/Tinymce";
import { Plus, SemiSelect, CircleCloseFilled } from "@element-plus/icons-vue";
import { getAppletsCode } from "@/api/tool";
import { ElMessageBox } from "element-plus"
import { addEventsInfo, editEventsInfo, getEventsInfoDetail, getBasicDataByCode } from "@/api/eventsinfo.js";
const store = useStore();
const router = useRouter();
const params = ref({});
const myEditor = ref(null);
const isStartEventCopy = ref(false)
const _POST = {
  eventsName: "", //活动名称
  eventsExpensePerson: "", //活动费用（人）
  eventsExpensePet: "", //活动费用（宠物）
  eventsExpensePersonCopy: "", //活动费用（人）
  eventsExpensePetCopy: "", //活动费用（宠物）
  eventsAddress: "", //活动地址
  locationName: "", //活动地址名称
  signUpEnd: "", //结束时间（报名结束）
  signUpStart: "", //开始时间（报名结束）
  eventsStartTime: "", //活动开始时间
  eventsEndTime: "", //活动结束时间
  sponsor: "", //主办单位
  undertaker: "", //承办单位
  eventsStatus: 0, //上线状态
  detailedInfo: "", //详情
  warmTips: "",
  selfSupport: '0', //1自营 0非自营
  isConfigShare: 0, // 0不配置 1配置 活动分享配置
  feeConfigType: 1,
  deductionAmount: '',
  deductionLimitAmount: '',
  latitude: '',
  longitude: '',
  eventsStartDate: '',
  isConfigBiscuit: 0,
  previewId: '',
  isMerchant: false,
  eventsType: [],
  isPushConfig: 0,
  scanCodePrompt: '',
  listingTime: ''
}
const formRef = ref({})
watchEffect(() => {
  params.value = router.currentRoute.value.params;
});
watch(()=> router.currentRoute.value,(nv, to)=>{
  if (nv.name === to.name && nv.params.id) {
    operateFn.init()
  } else {
    myEditor.value.setContent('')
    operate.post = {
      ..._POST
    }
    operate.showAddress = false
    operate.isLoading = false
    operate.detail = {}
    operate.dataReady = true
    operate.shareImage = []
    operate.surfaceDrawing = []
    operate.receiptImage = []
    operate.detailImages = []
    operate.feeDataPost = { // 费用配置数据
      deductionConfigList: [],
      personPetNum: [''],
      otherType: []
    }
    operate.tableFeeData = []
  }
})

const { $data: operate, $fn: operateFn } = (()=>{
  const backup = {
    post: {
      ..._POST
    },
    imageKeys: ["surfaceDrawing","shareImage", "detailImages", "receiptImage"]
  };
  let checkSurfaceDrawingNotNull = (rule, value, callback) => {
    if (!$data.surfaceDrawing || $data.surfaceDrawing.length == 0) {
      return callback("请上传活动封面图！");
    }
    callback();
  };
  let checkShareImageNotNull = (rule, value, callback) => {
    if (!$data.shareImage || $data.shareImage.length == 0) {
      return callback("请上传活动分享图！");
    }
    callback();
  };
  let checkDetailImagesNotNull = (rule, value, callback) => {
    if (!$data.detailImages || $data.detailImages.length == 0) {
      return callback("请上传活动详情图！");
    }
    callback();
  };
  let checkReceiptImageNotNull = (rule, value, callback) => {
    if (!$data.receiptImage || $data.receiptImage.length == 0) {
      return callback("请上传活报名回执页二维码！");
    }
    callback();
  };
  let checkActiveShare = (rule, value, callback) => {
    if (value === 1) {
      if (!$data.post.deductionAmount || !$data.post.deductionLimitAmount) {
        callback("请填写活动分享配置");
      }
    }
    callback();
  }
  let checkActiveFee = (rule, value, callback) => {
    if (value === 1 && !$data.tableFeeData.length && $data.post.selfSupport === 1) {
      callback('请填写活动费用配置')
    }
    callback();
  }
  let checkXiaobgdikou = (rule, value, callback) => {
    if (value === 1) {
      const list = $data.feeDataPost.deductionConfigList
      for (let i = 0 ; i < list.length; i++){
        if (!list[i].biscuitAmount || !list[i].deductionAmount) {
          callback('请填写小饼干抵扣')
        }
      }
    }
    callback();
  }
  const $data = reactive({
    isEdit: false,
    post: {
      ...backup.post
    },
    showAddress: false, //地址选择展示
    isLoading: false, //正在上传数据？
    detail: {},
    dataReady: false,
    surfaceDrawing: [],
    receiptImage: [],
    shareImage: [],
    detailImages: [],
    DataByCode: [],
    rules: {
      surfaceDrawing: [
        {
          required: true,
          validator: checkSurfaceDrawingNotNull,
          trigger: "change",
        },
      ],
      shareImage: [
        {
          required: true,
          validator: checkShareImageNotNull,
          trigger: "change",
        },
      ],
      detailImages: [
        {
          required: true,
          validator: checkDetailImagesNotNull,
          trigger: "change"
        }
      ],
      receiptImage: [
        {
          required: true,
          validator: checkReceiptImageNotNull,
          trigger: "change"
        }
      ],
      eventsName: [
        { required: true, message: "请输入活动名称", trigger: "blur" },
      ],
      eventsExpensePerson: [
        { required: true, message: "请输入活动费用（人）", trigger: "blur" },
        { pattern: /^\d+(\.{0,1}\d{1,2}){0,1}$/, message: "请输入正数且最多保留两位小数" },
      ],
      eventsExpensePet: [
        { required: true, message: "请输入活动费用（宠物）", trigger: "blur" },
        { pattern: /^\d+(\.{0,1}\d{1,2}){0,1}$/, message: "请输入正数且最多保留两位小数" },
      ],
      eventsType: [
        { required: true, message: "请选择活动分类", trigger: "change" },
      ],
      eventsAddress: [
        { required: true, message: "请输入活动地址", trigger: "blur" },
      ],
      scanCodePrompt: [
        { required: true, message: "请输入扫码提示", trigger: "blur" },
      ],
      eventsStartDate: [
        { required: true, message: "请选择活动开始时间", trigger: "change" },
      ],
      signUpDate: [
        { required: true, message: "请选择活动报名时间", trigger: "blur" }
      ],
      isConfigShare: [
        {
          required: true,
          validator: checkActiveShare,
          trigger: "click",
        },
      ],
      isConfigBiscuit: [
        {
          required: true,
          validator: checkXiaobgdikou,
          trigger: "click",
        },
      ],
      feeConfigType: [
        {
          required: true,
          validator: checkActiveFee,
          trigger: "click",
        }
      ],
      detailedInfo: [
        { required: true, message: "请填写活动详情", trigger: "blur" },
      ]
    },
    feeDataPost: { // 费用配置数据
      deductionConfigList: [],
      personPetNum: [''],
      otherType: []
    },
    tableFeeData: [],
    dialogVisible: false,
    dialogPeoplePetVisible: false,
    isPeoplePetConfig: false,
    isCollectPeopleInfo: '1',
    isCollectPetInfo: '1',
    personConfig: {
      nameEnable: 1,
      sexEnable: 1,
      phoneEnable: 0,
      birthdayEnable: 0
    },
    petConfig: {
      nameEnable: 1,
      sexEnable: 1,
      breedEnable: 0,
      birthdayEnable: 0
    },
  });
  const $fn = {
    init() {
      $data.isMerchant = store.getters.userInfo?.role === '商户'
      if ($data.isMerchant) {
        $data.post.selfSupport = '1'
      }
      if (params.value.id) {
        $data.dataReady = false;
        getEventsInfoDetail(params.value.id).then((res) => {
          if (res.code === 0) {
            // myEditor.value.setContent('')
            $data.dataReady = true;
            $data.detail = { ...res.data };
            let keys = Object.keys(backup.post);
            for (let key of keys) {
              $data.post[key] = $data.detail[key];
            }
            $data.post.eventsType = res.data.eventsType.split(',')
            $data.surfaceDrawing = [{url: res.data.surfaceDrawing}]
            $data.shareImage = [{url: res.data.shareImage}]
            $data.receiptImage = [{url: res.data.receiptImage || ''}]
            // 活动banner图
            const _detailImages = []
            res.data.detailImageList.forEach((element) => {
              _detailImages.push({ url: element })
            })
            $data.detailImages = _detailImages
            // console.log($data.surfaceDrawing)
            $data.post.signUpDate = [
              operate.post.signUpStart,
              operate.post.signUpEnd
            ];
            $data.post.eventsStartDate = [
              operate.post.eventsStartTime,
              operate.post.eventsEndTime
            ];
            if(new Date(operate.post.signUpStart).getTime() <= new Date().getTime()){
              // $data.isStartEvent = true
              isStartEventCopy.value = true
            }
            $data.previewId = res.data.id
            $data.post.eventsExpensePerson = operate.post.eventsExpensePerson / 100
            $data.post.eventsExpensePet = operate.post.eventsExpensePet / 100
            $data.post.deductionAmount = operate.post.deductionAmount / 100
            $data.post.deductionLimitAmount = operate.post.deductionLimitAmount / 100
            // 小饼干
            const deduction = res.data.deductionConfigList
            const _arr = []
            for(let i = 0;i < deduction.length; i++){
              _arr.push({
                ...deduction[i],
                deductionAmount: deduction[i].deductionAmount / 100
              })
            }
            $data.feeDataPost.deductionConfigList = _arr
            // 费用组合
            $data.feeDataPost.otherType = res.data.feeType.otherType
            $data.feeDataPost.personPetNum = res.data.feeType.personPetNum
            const _fee = []
            const feeConfigList = res.data.feeConfigList
            for (let j = 0; j < feeConfigList.length; j ++) {
              _fee.push({
                ...feeConfigList[j],
                price: feeConfigList[j].price / 100
              })
            }
            $data.tableFeeData = _fee
            // 参与人信息
            if (JSON.stringify(res.data.personConfig) === '{}') {
              $data.isCollectPeopleInfo = '2'
            }
            if (JSON.stringify(res.data.petConfig) === '{}') {
              $data.isCollectPetInfo = '2'
            }
            $data.personConfig = res.data.personConfig
            $data.petConfig = res.data.petConfig
            // tinymce重新设置信息
            myEditor.value.setContent(res.data.detailedInfo)
            $data.isPeoplePetConfig = true
            $data.isEdit = res.data.eventsStatus !== -1
          }
        });
      } else {
        $data.dataReady = true;
      }
    },
    // 获取分类
    getDataByCode(){
      getBasicDataByCode({
        code: 'events_category'
      }).then(res => {
        if(res.code === 0) {
          $data.DataByCode = res.data
        }
      })
    },
    submitPre(formRef, operationType) {
      console.log(99999, $data?.post.feeConfigType)
      if (!formRef) return;
      formRef.validate(async(valid) => {
        if (valid) {
          if (
            new Date($data.post.signUpStart).getTime() >
            new Date($data.post.eventsStartTime).getTime()
          ) {
            ElMessage.warning("报名开始时间不能大于活动开始时间！");
            return;
          }
          if (!$data.surfaceDrawing || $data.surfaceDrawing.length == 0) {
            ElMessage.warning("请上传活动封面图！");
            return;
          }
          if (!$data.shareImage || $data.shareImage.length == 0) {
            ElMessage.warning("请上传活动分享图！");
            return;
          }
          if (!$data.detailImages || $data.detailImages.length == 0) {
            ElMessage.warning("请上传活动详情图！");
            return;
          }
          // 活动封面图
          const _surfaceDrawing = await $fn.getImageDimensions($data?.surfaceDrawing[0].url)
          if (_surfaceDrawing.width !== 220 || _surfaceDrawing.height !== 292) {
            ElMessage.warning("活动封面图尺寸不对")
            return
          }
          // 活动分享图
          const _shareImage = await $fn.getImageDimensions($data?.shareImage[0].url)
          if (_shareImage.width !== 480 || _shareImage.height !== 384) {
            ElMessage.warning("活动分享图尺寸不对")
            return
          }
          // 二维码图
          const _receiptImage = await $fn.getImageDimensions($data?.receiptImage[0].url)
          if (_receiptImage.width !== _receiptImage.height) {
            ElMessage.warning("活动二维码图尺寸不对")
            return
          }
          // 活动banner图
          const _detailImages = await $fn.getImageDimensions($data?.detailImages[0].url)
          if (_detailImages.width !== 750 || _detailImages.height !== 1000) {
            ElMessage.warning("活动banner图尺寸不对")
            return
          }
          if (!$data.isPeoplePetConfig && !params.value.id && $data.post.selfSupport === 1) {
            ElMessage.warning("请配置人宠信息配置")
            return
          }
          if (operationType === 0 && $data.post.eventsStatus === -1) {
            ElMessage.warning("请选择上下架状态")
            return
          }
          $fn.submitData(operationType)
        }
      })
    },
    async getImageDimensions (imageUrl) {
      const image = new Image();
      image.src = imageUrl;
      return new Promise((resolve, reject) => {
        image.onload = () => {
          resolve({
            width: image.width,
            height: image.height
          });
        };
        image.onerror = reject;
      })
    },
    submitData(operationType) {
      // 数据处理
      let req = {
        ...$data.post,
        surfaceDrawing: $data?.surfaceDrawing[0].url,
        shareImage: $data?.shareImage[0].url,
        receiptImage: $data?.receiptImage[0].url,
        detailImages: $data?.detailImages.map((item) => item.url),
        eventsExpensePerson: $data?.post.eventsExpensePerson*100,
        eventsExpensePet: $data?.post.eventsExpensePet*100,
        eventsType: $data?.post.eventsType.join(',')
      }
      if (operationType === 2) {
        delete req.eventsStatus
      }
      if ($data?.post.isConfigBiscuit === 1){ // 小饼干
        const arr = []
        const deduList =  $data?.feeDataPost.deductionConfigList
        for (let i = 0 ; i< deduList.length; i++) {
          arr.push({
            ...deduList[i],
            deductionAmount: Math.round(deduList[i].deductionAmount * 100)
          })
        }
        req.deductionConfigList = arr
      }
      if ($data?.post.feeConfigType === 1){ // 费用配置
        req.feeType = {
          personPetNum: $data?.feeDataPost.personPetNum,
          otherType: $data?.feeDataPost.otherType
        }
        const _m = []
        for(let j = 0;j < $data?.tableFeeData.length; j++){
          _m.push({
            ...$data?.tableFeeData[j],
            enable: $data?.tableFeeData[j].enable ? 1 : 0,
            price: Math.round($data?.tableFeeData[j].price * 100)
          })
        }
        req.feeConfigList = _m
      }
      if ($data?.post.isConfigShare === 1) { // 分享配置
        req.deductionAmount = Math.round($data?.post.deductionAmount * 100),
        req.deductionLimitAmount = Math.round($data?.post.deductionLimitAmount * 100)
      } 
      if ($data.isCollectPeopleInfo == '1') {
        req.personConfig = $data.personConfig
      }
      if ($data.isCollectPetInfo == '1') {
        req.petConfig = $data.petConfig
      }
      $data.isLoading = true;
      if (params.value.id) {
        editEventsInfo({ ...req, id: params.value.id, operationType }, 'PUT').then((res) => {
          if (res.code === 0) {
            if (operationType === 1) {
              $fn.getCode($data.previewId)
            } else {
              ElMessage.success("修改成功！")
              store
                .dispatch("tagsView/delView", { ...router.currentRoute.value })
                .then(() => {
                  router.replace({ path: "/eventsInfo/list" })
                })
            }
          }
          $data.isLoading = false
        })
      } else {
        addEventsInfo({...req, operationType}, 'post').then((res) => {
          if (res.code === 0) {
            if (operationType === 1) {
              $data.previewId = res.data
              $fn.getCode(res.data)
            } else {
              ElMessage.success("添加成功！")
              store
              .dispatch("tagsView/delView", { ...router.currentRoute.value })
              .then(() => {
                router.replace({ path: "/eventsInfo/list" })
              })
            }
          }
          $data.isLoading = false
        })
      }
    },
    getCode (id) {
      getAppletsCode({
        scene: 'mp4',
        page: 'events/eventsDetail',
        param: 'preview=true&id=' + id
      }).then(res => {
        console.log(res)
        if(res.code === 0){
          const blobData = "data:image/png;base64,"+ res.data
          ElMessageBox.alert(
            `<img src=${blobData} style='width: 360px'>`,
            '',
            {
              dangerouslyUseHTMLString: true,
            }
          )
        }
      })
    },
    beforeUpload(file, size) {
      return new Promise((resolve, reject) => {
        const _size = (size + 1) * 1024
        if (file.size > _size) {
          ElMessage.error(`图片大小不能超过 ${size}kb！, 当前大小为${(file.size / 1024).toFixed(1)}kb`);
          reject()
          return
        }
        resolve()
      })
    },
    afterUpload(list, type) {
      const url = list[0];
      if (!url) {
        $data.post[type] = "";
        $data[type] = undefined;
        return;
      }
      // $data.post[type] = "https://img.qumoyugo.com" + url.showUrl;
      $data[type] = [{ url: "https://img.qumoyugo.com" + url.showUrl }];
    },
    afterUploadDetailImg(list) {
      if (!list || !list[0]) {
        $data.post.detailImages = undefined;
        $data.detailImages = undefined;
        return;
      }
      $data.detailImages = [];
      for (let prop of list || []) {
        $data.detailImages.push({
          url: prop.showUrl
            ? "https://img.qumoyugo.com" + prop.showUrl
            : prop.url,
        });
      }
    },
    limitStackiDate(time) {
      // 如果没有后面的 -8.64e7 就是不可以选择今天的
      const beginDate = new Date().getTime() - 8.64e7;
      const endDate = new Date("2300-01-01 00:00:00").getTime();
      return beginDate > time.getTime() || endDate < time.getTime();
    },
    limitSignUpStartDate(time) {
      // 如果没有后面的 -8.64e7 就是不可以选择今天的
      const beginDate = new Date().getTime() - 8.64e7;
      const endDate = new Date(
        $data.post.eventsStartTime || "2300-01-01 00:00:00"
      ).getTime();
      return beginDate > time.getTime() || endDate < time.getTime();
    },
    limitStartDate(time) {
      // 如果没有后面的 -8.64e7 就是不可以选择今天的
      const beginDate = new Date($data.post.signUpEnd || new Date()).getTime() - 8.64e7;
      const endDate = new Date($data.post.eventsEndTime || "2300-01-01 00:00:00").getTime();
      return beginDate > time.getTime() || endDate < time.getTime();
    },
    signUpDateChange(datetime) {
      $data.post.signUpStart =
        !!datetime && datetime.length == 2 ? datetime[0] : "";
      $data.post.signUpEnd =
        !!datetime && datetime.length == 2 ? datetime[1] : "";
    },
    eventsDateChange(datetime) {
      $data.post.eventsStartTime =
        !!datetime && datetime.length == 2 ? datetime[0] : "";
      $data.post.eventsEndTime =
        !!datetime && datetime.length == 2 ? datetime[1] : "";
    },
    chooseAddress() {
      if (params.value.id) return false
      $data.showAddress = true;
    },
    getEventsAddress(mapData) {
      if (!isStartEventCopy.value) {
        $data.post.eventsAddress = mapData.eventsAddress;
        $data.post.longitude = mapData.longitude;
        $data.post.latitude = mapData.latitude;
        $data.post.locationName = mapData.poiname;
      }
    },
    // 费用组合配置
    gotoDispose(type) {
      if (!$data.feeDataPost.otherType) {
        $data.feeDataPost = { // 费用配置数据
          deductionConfigList: [],
          personPetNum: [''],
          otherType: []
        }
      }
      $data.dialogVisible = true
      if (!$data.tableFeeData.length && !type) {
        $fn._getComputeTableFee()
      }
    },
    // 费用组合配置
    gotoPeoplePet() {
      $data.dialogPeoplePetVisible = true
    },
    closePeoplePet() {
      $data.dialogPeoplePetVisible = false
      $data.isPeoplePetConfig = false
    },
    submitPeoplePet() {
      $data.isPeoplePetConfig = true
      $data.dialogPeoplePetVisible = false
    },
    changeSelfSupport(value){
      if (!value) {
        $data.post.isConfigShare = 0  
        $data.post.isConfigBiscuit = 0
        $data.feeDataPost.deductionConfigList = []
        $data.post.feeConfigType = 0
      } else {
        $data.post.feeConfigType = 1
      }
    },
    // 增加费用类型
    addFeeType () {
      $data.feeDataPost.otherType.push('')
      $fn._getComputeTableFee()
    },
    // 删除
    removeFeeType() {
      $data.feeDataPost.otherType = []
      $fn._getComputeTableFee()
    },
    // 增加选项
    addOption(index) {
      if (index === 0) {
        $data.feeDataPost.personPetNum.push('')
      } else {
        $data.feeDataPost.otherType.push('')
      }
      $fn._getComputeTableFee()
    },
    // 删除选项
    removeOption(index, nameIndex) {
      if (index === 0) {
        $data.feeDataPost.personPetNum.splice(nameIndex, 1)
      } else {
        $data.feeDataPost.otherType.splice(nameIndex, 1)
      }
      $fn._getComputeTableFee()
    },
    blurFeeType(){
      $fn._getComputeTableFee()
    },
    // 删除小饼干
    removeCookie(index){
      $data.feeDataPost.deductionConfigList.splice(index, 1)
    },
    // 新增小饼干
    addCookie(){
      $data.feeDataPost.deductionConfigList.push({biscuitAmount: '', deductionAmount: ''})
    },
    changeCookie(e){
      if (e === 1 && !$data.feeDataPost.deductionConfigList.length) {
        $fn.addCookie()
      }
    },
    submitFeeData(){
      if (!params.value.id) {
        for(let j = 0; j < $data.tableFeeData.length; j++) {
          if ($data.tableFeeData[j].enable && !$data.tableFeeData[j].price) {
            ElMessage.error('费用配置不正确')
            return false
          }
        }
      }
      $data.dialogVisible = false
      console.log($data.tableFeeData)
    },
    closeDispose() {
      $data.dialogVisible = false
      if (!params.value.id) {
        $data.tableFeeData = []
        $data.feeDataPost.personPetNum = ['']
        $data.feeDataPost.otherType = []
      }
    },
    // 动态算费用表格
    _getComputeTableFee(){
      const personPetNum = $data.feeDataPost.personPetNum
      const otherType = $data.feeDataPost.otherType
      const arr = []
      for (let i = 0; i < personPetNum.length; i++) {
        if (otherType.length !== 0){
          for(let j = 0; j < otherType.length; j++) {
            arr.push({
              personPetNum: personPetNum[i] || '',
              otherType: otherType[j] || '',
              price: $data.tableFeeData[i] ? $data.tableFeeData[i].price : '',
              enable: $data.tableFeeData[i] ? $data.tableFeeData[i].enable : false,
              stock: $data.tableFeeData[i] ? $data.tableFeeData[i].stock : 0
            })
          }
        } else {
          arr.push({
            personPetNum: personPetNum[i],
            price: $data.tableFeeData[i] ? $data.tableFeeData[i].price : '',
            enable: $data.tableFeeData[i] ? $data.tableFeeData[i].enable : false,
            stock: $data.tableFeeData[i] ? $data.tableFeeData[i].stock : 0
          })
        } 
      }
      $data.tableFeeData = arr
    }
  };
  $fn.init();
  $fn.getDataByCode()
  return {
    $data,
    $fn,
    formRef
  };
})()
</script>

  <style scoped lang="scss">
.submitBtn {
  float: right;
  margin-right: 40px;
}
.panel {
  background-color: #ffffff;
  padding: 12px;
  border-radius: 8px;
  .block-title {
    padding: 12px;
    color: rgb(172, 172, 172);
  }
  .checkbox-group {
    .setting-btn {
      color: #409eff;
      margin: 0 12px;
      vertical-align: top;
      cursor: pointer;
    }
  }
}
.isEmpty {
  color: rgb(172, 172, 172);
}
:deep(.el-form-item__label){
  white-space:pre-line;
}
.dialog-fee{
  .title{
    font-size: 16px;
    font-weight: bold;
    margin: 10px 0;
  }
  .fee-tp{
    display:flex;
    align-items: center;
    margin-top:10px;
    flex-wrap: wrap;
  }
  .fee-t-ipt{
    margin:0 20px 10px 10px;
    width:120px;
    position:relative
  }
}
</style>
